package batch.home;

import javax.xml.parsers.*;

import org.xml.sax.*;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.Date;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.*;

import java.util.Vector;
import java.util.Properties;
import java.io.*;
import java.net.*;

import java.sql.*;
import java.io.*;
import java.net.URL;
import batch.common.db.ConnectionManager;


     
import batch.common.report.*;

public class makeCpHtmlCze
{
    final String strJavaName = "CP Html Czech";
    final int    ILENG       = 5;

    private final String TODAY              = DateFormatUtils.format(new Date(), "yyyyMMdd");  //Get Current Date
    private final String MAILSUBJECT        = "CZE CP Html Batch Error(" + TODAY + ")";
    private final String FILE_PATH          = "/home02/nas/cze_pub/sm3/batch/html/";
    private final String ROOT_URL    = "http://cz.samsungmobile.com";

    String strContentName = "";
    String strPreviewUrl = "";
    String strContentID = "";
    String strUrl = "";
    
    String content_id = "";
    String content_name = "";
    String preview_url = "";
    String order_url = "";
    String content_link = "";
    String content_price = "";
    String more_link = "";
    String Phone_model = "";    
    String CP_URL_RINGTONES = "http://download.samsungmobile.cz/?NUM=5&MALL_ID=A1"; //Realtone 
    String CP_URL_WALLPAPERS = "http://download.samsungmobile.cz/?NUM=5&MALL_ID=08"; //Wallpaper 
    String CP_URL_GAMES = "http://download.samsungmobile.cz/?NUM=5&MALL_ID=04"; //Jave Game
    
    private StringBuffer sHtml = new StringBuffer();

    public makeCpHtmlCze(){
    	ringTonesWallPapersInit();
    	gamesInit();
    }
    
    public void ringTonesWallPapersInit(){
        BufferedReader bfrStringRT = null;
        BufferedReader bfrStringWP = null;
        StringBuffer sbfRTXml = new StringBuffer();
        StringBuffer sbfWPXml = new StringBuffer();

        Document docRT = null;
        Document docWP = null;
        NodeList nlTempRT = null;
        NodeList nlTempRT2 = null;
        NodeList nlTempWP = null;
        NodeList nlTempWP2 = null;
    	
        OutputStreamWriter fw = null;
        try{
				URLConnection urlConRT = new URL(CP_URL_RINGTONES).openConnection();
				URLConnection urlConWP = new URL(CP_URL_WALLPAPERS).openConnection();
				bfrStringRT = new BufferedReader(new InputStreamReader(urlConRT.getInputStream(), "ISO-8859-2"));
				bfrStringWP = new BufferedReader(new InputStreamReader(urlConWP.getInputStream(), "ISO-8859-2"));
			
	            String line = "";
	            Vector vtElemRT        			 = new Vector();
	            Vector vtElemWP        			 = new Vector();
	            Vector vRingtone     			 = new Vector();
	            Vector vWallpaper    			 = new Vector();
	            Vector vTmpRingTonesMore		 = new Vector();
	            Vector vTmpWallPaperMore		 = new Vector();

	            while ((line = bfrStringRT.readLine()) != null)
	            {
	                sbfRTXml.append(line.replaceAll("&", "&amp;"));
	            }
	            
	            while ((line = bfrStringWP.readLine()) != null)
	            {
	            	sbfWPXml.append(line.replaceAll("&", "&amp;"));
	            }
System.out.println("***************************************************************************************");
System.out.println(sbfRTXml);
System.out.println("***************************************************************************************");
System.out.println(sbfWPXml);
System.out.println("***************************************************************************************");
	            byte bRTxml[] = sbfRTXml.toString().getBytes("ISO-8859-2");
	            ByteArrayInputStream isRT = new ByteArrayInputStream(bRTxml);
	            byte bWPxml[] = sbfWPXml.toString().getBytes("ISO-8859-2");
	            ByteArrayInputStream isWP = new ByteArrayInputStream(bWPxml);

	            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	            docRT = docBuilder.parse(new InputSource(isRT));
	            docWP = docBuilder.parse(new InputSource(isWP));
	            Element elemRT = docRT.getDocumentElement();
	            Element elemWP = docWP.getDocumentElement();
	            elemRT.normalize();
	            elemWP.normalize();
	            nlTempRT = elemRT.getChildNodes();
	            nlTempWP = elemWP.getChildNodes();
	            
	                for(int x=0;x<nlTempRT.getLength();x++){
	                    if(nlTempRT.item(x).getChildNodes().getLength() > 0){
	                        vtElemRT.addElement(nlTempRT.item(x).getChildNodes());
	                    }
	                }
	                for(int x=0;x<nlTempWP.getLength();x++){
	                    if(nlTempWP.item(x).getChildNodes().getLength() > 0){
	                        vtElemWP.addElement(nlTempWP.item(x).getChildNodes());
	                    }
	                }
	                
	                for(int x=0;x<vtElemRT.size();x++){
	                    Element tmpElem = (Element)vtElemRT.elementAt(x);
	                    String strElem = tmpElem.getTagName();
	                    
	                    if(strElem.equals("ringtones")){
	                        nlTempRT2 = tmpElem.getElementsByTagName("more_link");
		                    String more_tmp = nlTempRT2.item(0).getFirstChild().getNodeValue();
		                    
		                    vTmpRingTonesMore.add(more_tmp); // More Link 
	                    }
	                    if(strElem.equals("ringtones")){
		                    for (int i = 0; i < ILENG; i++) {
		                        Properties pptNode = new Properties();
		                        
		                        nlTempRT = tmpElem.getElementsByTagName("content_id");
		                        pptNode.setProperty("content_id", nlTempRT.item(i).getFirstChild().getNodeValue());
		                        nlTempRT = tmpElem.getElementsByTagName("content_name");
		                        pptNode.setProperty("content_name", nlTempRT.item(i).getFirstChild().getNodeValue());
		                        nlTempRT = tmpElem.getElementsByTagName("preview_url");
		                        pptNode.setProperty("preview_url", nlTempRT.item(i).getFirstChild().getNodeValue());
		                        nlTempRT = tmpElem.getElementsByTagName("order_url");
		                        pptNode.setProperty("order_url", nlTempRT.item(i).getFirstChild().getNodeValue());
		                        nlTempRT = tmpElem.getElementsByTagName("content_link");
		                        pptNode.setProperty("content_link", nlTempRT.item(i).getFirstChild().getNodeValue());                        
		                                    
		                        vRingtone.addElement(pptNode); 
		                    }
	                    }
	                }
	                
	                for(int x=0;x<vtElemWP.size();x++){
	                    Element tmpElem = (Element)vtElemWP.elementAt(x);
	                    String strElem = tmpElem.getTagName();

	                    if(strElem.equals("wallpapers")){
	                    	nlTempWP2 = tmpElem.getElementsByTagName("more_link");
		                    String more_tmp = nlTempWP2.item(0).getFirstChild().getNodeValue();
		                    
		                    vTmpWallPaperMore.add(more_tmp); // More Link 
	                    }

	                    if(strElem.equals("wallpapers")){
	                    	for (int i = 0; i < 2; i++) {
		                        Properties pptNode = new Properties();
		                        
		                        nlTempWP = tmpElem.getElementsByTagName("content_id");
		                        pptNode.setProperty("content_id", nlTempWP.item(i).getFirstChild().getNodeValue());
		                        nlTempWP = tmpElem.getElementsByTagName("content_name");
		                        pptNode.setProperty("content_name", nlTempWP.item(i).getFirstChild().getNodeValue());
		                        nlTempWP = tmpElem.getElementsByTagName("preview_url");
		                        pptNode.setProperty("preview_url", nlTempWP.item(i).getFirstChild().getNodeValue());
		                        nlTempWP = tmpElem.getElementsByTagName("order_url");
		                        pptNode.setProperty("order_url", nlTempWP.item(i).getFirstChild().getNodeValue());
		                        nlTempWP = tmpElem.getElementsByTagName("content_link");
		                        pptNode.setProperty("content_link", nlTempWP.item(i).getFirstChild().getNodeValue());                        
		                                    
		                        vWallpaper.addElement(pptNode); 
		                    }
	                    }
	                }

	            File fl = new File(FILE_PATH);
	
	            if(!fl.isDirectory()){
	                fl.mkdirs();
	            }
	            if(vRingtone.size() > 0 || vWallpaper.size() > 0){
	            	getRingtoneWallpaper(vRingtone,vWallpaper,vTmpRingTonesMore,vTmpWallPaperMore);
	            }
        }catch(Exception ex){
            ex.printStackTrace();
            Logger.getLogger("home.cze_ringtoneWallpaper").info(ex.toString());
            ReportError.byEmail(MAILSUBJECT, ex.toString());
        }finally {
            if(bfrStringRT != null || bfrStringWP != null) try { bfrStringRT.close(); bfrStringWP.close();} catch (Exception e) {}
        }
    }

    public void gamesInit(){
        BufferedReader bfrString = null;
        StringBuffer sbfXml = new StringBuffer();

        Document doc = null;
        NodeList nlTemp = null;
        NodeList nlTemp2 = null;
    	
        OutputStreamWriter fw = null;
        
        try{
				URLConnection urlCon = new URL(CP_URL_GAMES).openConnection();
	            bfrString = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "ISO-8859-2"));
	
	            String line = "";
	            Vector vtElem        = new Vector();
	            Vector vGames        = new Vector();
 
	            Vector vTmpMore		 = new Vector();

	            while ((line = bfrString.readLine()) != null)
	            {
	                sbfXml.append(line.replaceAll("&", "&amp;"));
	            }
	            System.out.println("***************************************************************************************");
	            System.out.println(sbfXml);
	            System.out.println("***************************************************************************************");
	            byte bxml[] = sbfXml.toString().getBytes("ISO-8859-2");
	            ByteArrayInputStream is = new ByteArrayInputStream(bxml);

	            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	            doc = docBuilder.parse(new InputSource(is));
	            Element elem = doc.getDocumentElement();
	            elem.normalize();

	            nlTemp = elem.getChildNodes();
	            
	                for(int x=0;x<nlTemp.getLength();x++){
	                    if(nlTemp.item(x).getChildNodes().getLength() > 0){
	                        vtElem.addElement(nlTemp.item(x).getChildNodes());
	                    }
	                }
	                
	                for(int x=0;x<vtElem.size();x++){
	                    Element tmpElem = (Element)vtElem.elementAt(x);
	                    String strElem = tmpElem.getTagName();

                        nlTemp2 = tmpElem.getElementsByTagName("more_link");
	                    String more_tmp = nlTemp2.item(0).getFirstChild().getNodeValue();
	                    
	                    vTmpMore.add(more_tmp); // More Link 
                        
	                    for (int i = 0; i < ILENG; i++) {
	                        Properties pptNode = new Properties();
	                        
	                        nlTemp = tmpElem.getElementsByTagName("content_id");
	                        pptNode.setProperty("content_id", nlTemp.item(i).getFirstChild().getNodeValue());
	                        nlTemp = tmpElem.getElementsByTagName("content_name");
	                        pptNode.setProperty("content_name", nlTemp.item(i).getFirstChild().getNodeValue());
	                        nlTemp = tmpElem.getElementsByTagName("preview_url");
	                        pptNode.setProperty("preview_url", nlTemp.item(i).getFirstChild().getNodeValue());
	                        nlTemp = tmpElem.getElementsByTagName("order_url");
	                        pptNode.setProperty("order_url", nlTemp.item(i).getFirstChild().getNodeValue());
	                        nlTemp = tmpElem.getElementsByTagName("content_link");
	                        pptNode.setProperty("content_link", nlTemp.item(i).getFirstChild().getNodeValue());                        
	                        
	                        if(strElem.equals("games")){
	                            vGames.addElement(pptNode);
	                        }	                                               
	                  }
	                }
	
	            File fl = new File(FILE_PATH);
	
	            if(!fl.isDirectory()){
	                fl.mkdirs();
	            }

	            if(vGames.size() > 0){
	            	getGame(vGames,vTmpMore);
	            }  
        }catch(Exception ex){
            ex.printStackTrace();
            Logger.getLogger("home.cze_games").info(ex.toString());
            ReportError.byEmail(MAILSUBJECT, ex.toString());
        }finally {
            if(bfrString != null) try { bfrString.close(); } catch (Exception e) {}
        }
    }

    public void getRingtoneWallpaper(Vector vRingtone, Vector vWallpaper, Vector vTmpRingTonesMore, Vector vTmpWallPaperMore) throws Exception  {
        OutputStreamWriter fw = null;

        String moreTmpRingTonesLink = "";
        if (vTmpRingTonesMore != null || vTmpRingTonesMore.equals("")) moreTmpRingTonesLink = (String)vTmpRingTonesMore.elementAt(0);        
        String moreTmpWallPaperLink = "";
        if (moreTmpWallPaperLink != null || moreTmpWallPaperLink.equals("")) moreTmpWallPaperLink = (String)vTmpWallPaperMore.elementAt(0);        
        
        
        try{
            sHtml.setLength(0);
            
            sHtml.append("<div class='leftA'>\n")
            .append("		<dl class='mboxG'>\n")
            .append("			<dt>\n")
            .append("				<a href=\""+moreTmpRingTonesLink+"\">Reálná vyzvánění</a>\n")
            .append("				<a href=\""+moreTmpRingTonesLink+"\" class='more'>Více</a>\n")
            .append("			</dt>\n")
            .append("			<dd>\n")
            .append("				<ul class='dotList'>\n");

            if(vRingtone.size() > 0) {
            	for(int i=0; i<vRingtone.size(); i++){
	                Properties pContentList = (Properties) vRingtone.elementAt(i);
	                content_id = StringUtils.defaultString(pContentList.getProperty("content_id"),"");
	                content_name = StringUtils.defaultString(pContentList.getProperty("content_name"),"");
	                preview_url = StringUtils.defaultString(pContentList.getProperty("preview_url"),"");
	                order_url = StringUtils.defaultString(pContentList.getProperty("order_url"),"");
	                content_link = StringUtils.defaultString(pContentList.getProperty("content_link"),"");           

	                if(content_name.length() >= 21){
	                	content_name = content_name.substring(0, 21) + "..";
	                }	                
	                
	                sHtml.append("			<li title='"+content_name+"'>\n")		
	                	 .append("				<a href=\""+content_link+"\">\n")
	                	 .append("				"+content_name+"\n")
	                	 .append("				</a>\n")
	                	 .append("				<div class='p_btnA'>\n")
	                	 .append("				<a href=\""+content_link+"\"><img src=\""+ROOT_URL+"/image/common/btn_buy.gif\" alt='koupit'></a>\n")
	                	 .append("				</div>\n")
		                 .append("				<input type=\"hidden\" name=\"filepath"+(i+1)+"\"   id=\"filepath"+(i+1)+"\"  	value=\"\" >\n")
		                 .append("				<input type=\"hidden\" name=\"filename"+(i+1)+"\"   id=\"filename"+(i+1)+"\"  	value=\""+preview_url+"\" >\n")
		                 .append("				<input type=\"hidden\" name=\"artist"+(i+1)+"\"     id=\"artist"+(i+1)+"\" 		value=\"\" >\n")
		                 .append("				<input type=\"hidden\" name=\"title"+(i+1)+"\"      id=\"title"+(i+1)+"\" 		value=\""+content_name+"\" >\n")
		                 .append("				<input type=\"hidden\" name=\"order_url"+(i+1)+"\"  id=\"order_url"+(i+1)+"\" 	value=\""+order_url+"\" >\n")
		                 .append("			</li>\n");
            	}
            }
            sHtml.append("			</ul>\n")
            	 .append("		</dd>\n")
            	 .append("	</dl>\n")    
            	 .append("</div>\n");
            
            sHtml.append("<div class='rightA'>\n")
            	 .append("	<dl class='mboxG'>\n")
            	 .append("		<dt>\n")
            	 .append("		    <a href=\""+moreTmpWallPaperLink+"\">Tapety</a> <a href=\""+moreTmpWallPaperLink+"\" class='more'>Více</a>\n")
            	 .append("		</dt>\n")
            	 .append("		<dd>\n")
            	 .append("		    <ul>\n");
    		if(vWallpaper.size() > 0) {
    			for(int i=0; i<vWallpaper.size(); i++){
    				Properties pContentList = (Properties) vWallpaper.elementAt(i);
	                content_id = StringUtils.defaultString(pContentList.getProperty("content_id"),"");
	                content_name = StringUtils.defaultString(pContentList.getProperty("content_name"),"");
	                preview_url = StringUtils.defaultString(pContentList.getProperty("preview_url"),"");
	                order_url = StringUtils.defaultString(pContentList.getProperty("order_url"),"");
	                content_link = StringUtils.defaultString(pContentList.getProperty("content_link"),"");           

	                if(content_name.length() >= 21){
	                	content_name = content_name.substring(0, 21) + "..";
	                }
	                
	                sHtml.append("			<li class='leftA'>\n")	
	                	 .append("				<div class='imgBox77'><a href=\""+content_link+"\" style='cursor:pointer'>\n")
	                	 .append("				<img src=\""+preview_url+"\" alt='"+content_name+"' title='"+content_name+"' width='77' height='77'>\n")
	                	 .append("			</a></div>\n")
	                	 .append("			<p class='p_tit'><a href='"+content_link+"'><img src="+ROOT_URL+"/image/common/btn_buy.gif alt='koupit'></a></p>\n")
	                	 .append("			</li>\n");
    			}
    		}
    		sHtml.append("			</ul>\n")
    			.append("		</dd>\n")
    			.append("	</dl>\n")
    			.append("</div>\n");
            
            fw = new OutputStreamWriter(new FileOutputStream(FILE_PATH + "/homeringtone_include.html",false), "ISO-8859-2");
            fw.write(sHtml.toString());
            fw.close();

        }finally{
            if (fw != null) try { fw.close(); } catch (Exception e) {}
        }
    }    

    
    public void getGame(Vector pVector, Vector vMore) throws Exception  {
        OutputStreamWriter fw = null;
        String moreLink = "";
        if (vMore != null || vMore.equals("")) moreLink = (String)vMore.elementAt(0);
        try{
            /* Front MAIN Page Game*/
            sHtml.setLength(0);
            
            sHtml.append("<form name=mobileFrm id=mobileFrm method=post action="+moreLink+">")
            .append("<dt>\n")
            .append("<a href='"+moreLink+"'>Hry</a><a href='"+moreLink+"' class='more'>Více</a>\n")
            .append("</dt>\n")
            .append("<dd class='mCon'>\n")
            .append("	<div class='goodsList'>\n")
            .append("		<ul>\n");

            if(pVector.size() > 0) {
            	for(int i=0; i<pVector.size(); i++){
	                Properties pContentList = (Properties) pVector.elementAt(i);
	                content_id = StringUtils.defaultString(pContentList.getProperty("content_id"),"");
	                content_name = StringUtils.defaultString(pContentList.getProperty("content_name"),"");
	                preview_url = StringUtils.defaultString(pContentList.getProperty("preview_url"),"");
	                order_url = StringUtils.defaultString(pContentList.getProperty("order_url"),"");
	                content_link = StringUtils.defaultString(pContentList.getProperty("content_link"),"");        
	            
	                if(content_name.length() >= 13){
	                	content_name = content_name.substring(0, 13) + "..";
	                } 	                	                
	                
		            sHtml.append("			<li>\n")
			             .append("				<div class='imgBox77'><a href='"+content_link+"'><img src='"+preview_url+"' alt='"+content_name+"' width=77 height=77></a></div>\n")
			             .append("				<p class='p_tit'>"+content_name+" </p>\n")
			             .append("				<div class='p_btnA'>\n")
			             .append("					<a href='"+content_link+"'><img src="+ROOT_URL+"/image/common/btn_detail.gif alt='detail'></a>\n")
			             .append("					<a href='"+order_url+"'><img src="+ROOT_URL+"/image/common/btn_buy.gif alt='koupit'></a>\n")
			             .append("				</div>\n")
			             .append("			</li>\n");
            	}
            }
            sHtml.append("		</ul>\n")
            .append("	</div>\n")
            .append("</form>\n")            
            .append("</dd>\n");
            fw = new OutputStreamWriter(new FileOutputStream(FILE_PATH + "/homegame_include.html",false), "ISO-8859-2");
            fw.write(sHtml.toString());
            fw.close();

        }finally{
            if (fw != null) try { fw.close(); } catch (Exception e) {}
        }
    }
    
    public static void main( String[] args ){
      Logger.getLogger("home.cze_home").info("( * ) Start.");
      makeCpHtmlCze mvm = new makeCpHtmlCze();
      Logger.getLogger("home.cze_home").info("( * ) End.");
    }
}